﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bot.Domain
{
    public class EnumConverter : StringEnumConverter
    {

        public override bool CanConvert(Type objectType)
        {

            return true;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Type t;

            bool allowNull = false;
            if (objectType.GetGenericArguments().Length == 0)
            {
                t = objectType;
            }
            else
            {
                t = objectType.GetGenericArguments()[0];
                allowNull = true;
            }

            List<string> enums = System.Enum.GetNames(t).ToList();
            if (!allowNull)
            {
                if (reader.Value == null || reader.Value.GetType() != typeof(System.String) | !enums.Contains(reader.Value))
                    return "";
            }
            else
            {
                if (reader.Value != null && (reader.Value.GetType() != typeof(System.String) || !enums.Contains(reader.Value)))
                    return "";
            }



            return new JsonSerializer().Deserialize(reader, objectType);
        }

        public override bool CanRead
        {
            get
            {
                return true;
            }
        }



    }
}
